package com.erdos.core.service.impl;

import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ResourceBundleMessageSource;

import com.erdos.common.exception.BaseRuntimeException;
import com.erdos.common.util.StringUtil;
import com.erdos.core.service.CommonService;

 
public class CommonServiceImpl implements CommonService {

    private ResourceBundleMessageSource messageSource;

    public String getI18nErrorMessage(Exception e) {
        String errorMsg = null;
        if (e instanceof BaseRuntimeException) {
            BaseRuntimeException exception = (BaseRuntimeException) e;
            String code = exception.getCode();
            Object[] args = exception.getParams();
            // 是否定义了国际化
            try {
                errorMsg = messageSource.getMessage(code, args, null);
            } catch (NoSuchMessageException ex) {
            }
        }
        // 容错处理，如果没有定义国际化
        if (StringUtil.isBlank(errorMsg)) {
            errorMsg = e.getMessage();
            errorMsg = errorMsg == null ? null : errorMsg.replaceAll("\n", " ");
        }
        return errorMsg;
    }

    /**
     * @return the messageSource
     */
    public ResourceBundleMessageSource getMessageSource() {
        return messageSource;
    }

    /**
     * @param messageSource the messageSource to set
     */
    public void setMessageSource(ResourceBundleMessageSource messageSource) {
        this.messageSource = messageSource;
    }

}
